/*
 * @Author: xuetao 3168581151@qq.com
 * @Date: 2025-02-15
 * @LastEditors: xuetao 3168581151@qq.com
 * @LastEditTime: 2025-03-15
 * @Description: 
 */

import 'package:chat_client/enums/chat_enum.dart';
import 'package:chat_client/models/contact_model.dart';
import 'package:chat_client/models/session_model.dart' show SessionModel;
import 'package:chat_client/providers/chat_provider.dart';
import 'package:chat_client/services/contact_service.dart' show ContactService;
import 'package:chat_client/utils/route_tools.dart' show splitChatPath;
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'widgets/message_bubble.dart';
import 'widgets/input_bar.dart';
import 'package:chat_client/screens/chat/widgets/floating_bubble.dart';

class ChatScreen extends StatefulWidget {
  final String? pathStr;
  final SessionModel? session;

  const ChatScreen({
    super.key,
    this.pathStr,
    this.session,
  });

  @override
  ChatScreenState createState() => ChatScreenState();
}

class ChatScreenState extends State<ChatScreen> {
  final ContactService _contactService = ContactService.instance;

  final GlobalKey<InputBarState> inputBarKey = GlobalKey();
  final GlobalKey _anchorKey = GlobalKey();

  late SessionModel _session;

  @override
  void initState() {
    _loadSessionObject();
    super.initState();
  }

  _loadSessionObject() {
    if (widget.session != null) {
      _session = widget.session!;
      return;
    }
    // 路由转跳
    if (widget.pathStr != null) {
      final session = splitChatPath(widget.pathStr!);
      if (session.type == ConversationType.user.value) {
        final Contact contact = _contactService.getLocalContact(session.id);
        _session = SessionModel(
          conversationId: contact.conversationId,
          type: session.type,
          id: session.id,
          name: contact.nickname,
        );
      }
    }
  }

  double _initAnchor(int length) {
    final anchor = length / 12;
    if (anchor < 1.0) return anchor;
    return 1.0;
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (_) => ChatProvider(_session),
      child: Consumer<ChatProvider>(
        builder: (context, model, child) {
          return Scaffold(
            // 禁用系统默认的键盘挤压行为
            resizeToAvoidBottomInset: false,
            appBar: AppBar(
              title: Text(_session.name),
              actions: [
                IconButton(onPressed: () {}, icon: Icon(Icons.more_horiz))
              ],
            ),
            body: Stack(
              children: [
                Column(
                  children: [
                    Expanded(
                      child: GestureDetector(
                        child: CustomScrollView(
                          controller: model.scrollController,
                          physics: const BouncingScrollPhysics(),
                          // scrollBehavior: ScrollBehavior,控制滚动行为样式
                          // 视口外的缓存范围
                          keyboardDismissBehavior:
                              ScrollViewKeyboardDismissBehavior.onDrag,
                          center: _anchorKey,
                          anchor: _initAnchor(model.oldMessages.length),
                          slivers: [
                            // 旧消息列表
                            SliverList(
                                delegate: _buildOldMessageDelegate(model)),
                            // 定位
                            SliverPadding(
                                key: _anchorKey, padding: EdgeInsets.zero),
                            // 新消息列表
                            SliverList(
                                delegate: _buildNewMessageDelegate(model)),
                          ],
                        ),
                        // 关闭底部面板
                        onTap: () => inputBarKey.currentState?.closePanel(),
                      ),
                    ),
                    // web 输入区域
                    // mobile 输入区域
                    CompositedTransformTarget(
                      link: model.layerLink,
                      child: InputBar(
                        session: _session,
                        key: inputBarKey,
                        textController: model.messageController,
                        onSend: (dynamic text) {
                          model.handleSend(text);
                        },
                      ),
                    ),
                  ],
                ),
                // 未读消息数量气泡
                if (model.unreadCount > 0)
                  FloatingFloating(
                    layerLink: model.layerLink,
                    jumpTo: model.jumpToBottom,
                    unreadCount: model.unreadCount,
                  )
              ],
            ),
          );
        },
      ),
    );
  }

  // 旧消息列表的 delegate
  SliverChildBuilderDelegate _buildOldMessageDelegate(ChatProvider model) {
    return SliverChildBuilderDelegate(
      (context, index) => ChatBubble(
        message: model.oldMessages[index],
        userId: model.userId,
        isGroup: _session.type == ConversationType.group.value,
      ),
      childCount: model.oldMessages.length,
    );
  }

  // 新消息列表的 delegate
  SliverChildBuilderDelegate _buildNewMessageDelegate(ChatProvider model) {
    return SliverChildBuilderDelegate(
      (context, index) => ChatBubble(
        message: model.newMessages[index],
        userId: model.userId,
        isGroup: _session.type == ConversationType.group.value,
      ),
      childCount: model.newMessages.length,
    );
  }
}
